#!/usr/bin/env bash
SELFDIR=$(cd $(dirname "${BASH_SOURCE[0]}");pwd)
HOST_ARCH=$(arch | tr '[:upper:]' '[:lower:]')
PKGR="${SELFDIR}/.pkgr/bin/pkgr-${HOST_ARCH}"

#   $1 message
function error()
{
    echo -e "\e[31m$@\e[0m"
}

#   $1 message
function infor()
{
    echo -e "\e[32m$@\e[0m"
}

#   $1 init
function cmd_init()
{
    #   编译 pkgr 二进制工具
    cd "${PKGREPO}/.pkgr" && "${PKGREPO}/.pkgr/install.sh"
    RESULT=$?
    if [[ ${RESULT} -ne 0  || ! -f "${PKGR}" ]]; then
        error   "Build pkgr failed: '${PKGREPO}/.pkgr'"
        return  1
    fi

    return 0
}

# $1 install
# $2 label   : module_name/module_version
function cmd_install_modlabel()
{
    #   提取模块标签和模块切片列表
    local module_label="$2"

    infor "[INSTALL] ${module_label} : ..."

    if [[ ! -f "${PKGR}" ]]; then
        error   "[FAIL] The required tool 'pkgr' is missing: '${PKGR}'"
        return  1
    fi

    #   执行安装
    # echo "[install] ${module_label}"
    cd "${DEVREPO}" && "${PKGR}" "$@"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        error   "[FAIL] ${module_label} : Install module failed(${RESULT})"
        return  1
    fi

    infor   "[ OK ] ${module_label} : Install module success: '${DEVREPO}/${module_label}'"
    return  0
}

# $1 install
# $2 label   : env_file@env_slice
function cmd_install_envlabel()
{
    #   source init.bash plan@view
    local env_label="$2"
    local env_file=$(echo  "${env_label}" | sed 's#@# #g' | awk '{print $1}')
    local env_slice=$(echo "${env_label}" | sed 's#@# #g' | awk '{print $2}')

    if [[ ! -f "${DEVREPO}/${env_file}" ]]; then
        error   "[FAIL] Can not found file '${DEVREPO}/${env_file}'"
        return  1
    fi

    local fail_count=0
    local succ_count=0

    #   逐行读取环境文件
    while read line; do
        #   跳过空白行
        if [[ "${line}" =~ ^\s*#.*$ ]]; then
            continue
        fi

        #   拆分标签和切片
        local module_label=$(echo "${line}" | awk '{print $1}')
        local module_slice_list=$(echo "${line}"  | awk '{print $2}' | sed 's#:# #g')

        #   匹配环境切片
        local module_matched="no"
        for slice_item in ${module_slice_list}; do
            if [[ "${slice_item}" == "${env_slice}" ]]; then
                module_matched="yes"
                break
            fi
        done

        #   如果切片不匹配，那么跳过该模块
        if [[ "${module_matched}" == "no" ]]; then
            continue
        fi

        #   安装指定的模块
        cmd_install_modlabel install "${module_label}"
        RESULT=$?
        if [[ ${RESULT} -ne 0 ]]; then
            fail_count=$((fail_count + 1))
            return  1
        fi

        #   安装成功，刷新安装环境
        succ_count=$((succ_count + 1))
        source "${DEVREPO}/${module_label}/setup.bash"

        continue
    done < "${DEVREPO}/${env_file}"

    #   统计下失败的数量
    if [[ ${fail_count} -ne 0 ]]; then
        return  1
    fi

    return  0
}

# $1 install
# $2 label   : env_file@env_slice or module_name/module_version
function cmd_install()
{
    #   参数数量不对
    if [[ $# -lt 2 ]]; then
        error   "[FAIL] Missing parameter for '$1', try -h for help"
        return  1
    fi

    #   包仓库
    if [[ ! -d "${PKGREPO}" ]]; then
        error   "[FAIL] The required environment variable \${PKGREPO} is missing"
        return  1
    fi

    #   环境仓库
    if [[ ! -d "${DEVREPO}" ]]; then
        error   "[FAIL] The required environment variable \${DEVREPO} is missing"
        return  1
    fi

    #   根据制定的是环境标签，还是模块标签来决定采用什么方式安装
    local label="$2"
    if   [[ "${label}" =~ [^@/]+/.+ ]]; then
        cmd_install_modlabel "$@"
        return  $?
    elif [[ "${label}" =~ [^@/]+@.+ ]]; then
        cmd_install_envlabel "$@"
        return  $?
    fi

    error   "[FAIL] Unsupported label format '${label}'"
    return  1
}


function main()
{
    if [[ $# -ge 1 && "$1" == "init" ]]; then
        cmd_init    "$@"
        return      "$?"
    fi

    if [[ $# -ge 1 && "$1" == "install" ]]; then
        cmd_install "$@"
        return      "$?"
    fi

    if [[ ! -f "${PKGR}" ]]; then
        error   "[FAIL] The PKGREPO is not initialized, try type 'pkgr init' to make the initialization"
        return  1
    fi

    exec   "${PKGR}"   "$@"
    return ${RESULT}
}

main    "$@"
exit    "$?"
